package com.admin.infrastructure.persistence.jdbc;

import com.admin.domain.modle.Advert;
import com.admin.domain.repository.AdvertRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * description
 * User: WeiDa
 * Date: 2017-4-13
 * Time: 20:38
 */
@Repository
public class AdvertRepositoryJdbc implements AdvertRepository {

    @Autowired
    protected JdbcTemplate jdbcTemplate;

    @Override
    public void add(Advert advert) {
        jdbcTemplate.update("INSERT INTO advert (id,title,url,img_url) VALUES (?,?,?,?)", advert.getId(), advert.getTitle(), advert.getUrl(), advert.getImgUrl());
    }

    @Override
    public void update(Advert advert) {
        jdbcTemplate.update("UPDATE advert SET title=?,url=?,img_url=? WHERE `id`=?", advert.getTitle(), advert.getUrl(), advert.getImgUrl(), advert.getId());
    }

    @Override
    public Advert get(String id) {
        return jdbcTemplate.queryForObject("select * from advert where id=?", BeanPropertyRowMapper.newInstance(Advert.class), id);
    }

    @Override
    public List<Advert> list(String key) {
        if (StringUtils.isEmpty(key)) {
            return jdbcTemplate.query("select * from advert", BeanPropertyRowMapper.newInstance(Advert.class));
        } else {
            return jdbcTemplate.query("select * from advert WHERE title like ?",
                    BeanPropertyRowMapper.newInstance(Advert.class), "%" + key + "%");
        }
    }

    @Override
    public void remove(String id) {
        jdbcTemplate.update("DELETE FROM advert WHERE id=?", id);
    }


}
